import { View, Text, StyleSheet, ScrollView, TouchableOpacity, Image, RefreshControl, FlatList, Alert } from 'react-native';
import { useState, useEffect, useCallback } from 'react';
import { userService, artworkService, communityService } from '../../utils/api/services';
import { API_BASE_URL } from '../../utils/api/config';
import { MaterialIcons } from '@expo/vector-icons';
import { useRouter, useLocalSearchParams } from 'expo-router';
import { ArtworkResponse, TopicResponse } from '../../utils/api/types';
import { formatDate } from '../../utils/date';
import { useAuth } from '../../store/auth/AuthContext';
import Toast from 'react-native-toast-message';
import { ThemeToggle } from '../../components/theme/ThemeToggle';
import { useTheme } from '../../components/theme/ThemeContext';

// 添加文件类型图标映射
const FILE_TYPE_ICONS = {
  'video': 'videocam' as const,
  'image': 'image' as const,
  'audio': 'audiotrack' as const,
  'text': 'description' as const,
  'application': 'insert-drive-file' as const,
};

// 获取文件类型对应的图标
const getFileTypeIcon = (fileType: string) => {
  const type = fileType.split('/')[0];
  return FILE_TYPE_ICONS[type as keyof typeof FILE_TYPE_ICONS] || FILE_TYPE_ICONS.application;
};

export default function MeScreen() {
  const router = useRouter();
  const { refresh } = useLocalSearchParams();
  const { user, logout: authLogout } = useAuth();
  const { theme } = useTheme();
  const [userInfo, setUserInfo] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [artworks, setArtworks] = useState<ArtworkResponse[]>([]);
  const [topics, setTopics] = useState<TopicResponse[]>([]);

  // 获取用户信息
  const fetchUserInfo = useCallback(async () => {
    if (!user?.id) {
      console.error('未获取到用户ID');
      Toast.show({
        type: 'error',
        text1: '获取用户信息失败',
        text2: '请重新登录',
      });
      router.replace('/user/login');
      return;
    }

    try {
      setLoading(true);
      console.log('当前登录用户ID:', user.id);
      console.log('当前用户信息:', user);
      
      const userId = Number(user.id);
      const response = await userService.getUser(userId);
      console.log('获取到的用户信息:', response?.data);
      
      if (response?.data) {
        setUserInfo(response.data);
      }

      // 获取用户作品列表
      const artworksResponse = await artworkService.listArtworks({ limit: 10 });
      console.log('作品列表原始数据:', artworksResponse);
      
      if (artworksResponse?.code === 200 && Array.isArray((artworksResponse as any)?.data?.items)) {
        // 在前端过滤当前用户的作品
        const userArtworks = (artworksResponse as any).data.items.filter(
          (artwork: ArtworkResponse) => {
            console.log('比较作品:', artwork.creator_id, userId);
            return artwork.creator_id === userId;
          }
        );
        console.log('过滤后的用户作品:', userArtworks);
        setArtworks(userArtworks);
      }

      // 获取用户话题列表
      const topicsResponse = await communityService.listTopics();
      console.log('话题列表原始数据:', topicsResponse);
      
      if (topicsResponse?.code === 200 && Array.isArray(topicsResponse?.data?.data)) {
        // 只显示当前用户的话题
        const userTopics = topicsResponse.data.data.filter(topic => {
          console.log('比较话题:', topic.user_id, userId);
          return topic.user_id === userId;
        });
        console.log('过滤后的用户话题:', userTopics);
        setTopics(userTopics);
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
      Toast.show({
        type: 'error',
        text1: '获取数据失败',
        text2: '请下拉刷新重试',
      });
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  }, [user?.id, router]); // 添加 router 到依赖项

  // 处理下拉刷新
  const onRefresh = useCallback(() => {
    setRefreshing(true);
    fetchUserInfo();
  }, [fetchUserInfo]);

  // 监听refresh参数变化，重新获取用户信息
  useEffect(() => {
    fetchUserInfo();
  }, [fetchUserInfo, refresh]);

  const handleEditProfile = () => {
    router.navigate('/user/edit-profile');
  };

  const handleLogout = async () => {
    // 显示确认对话框
    Alert.alert(
      '退出登录',
      '确定要退出登录吗？',
      [
        {
          text: '取消',
          style: 'cancel',
        },
        {
          text: '确定',
          style: 'destructive',
          onPress: async () => {
            try {
              // 调用后端退出登录接口
              await userService.logout();
              
              // 清除本地认证状态
              await authLogout();
              
              // 显示成功提示
              Toast.show({
                type: 'success',
                text1: '退出成功',
              });

              // 跳转到登录页面
              router.replace('/user/login');
            } catch (error) {
              console.error('退出登录失败:', error);
              Toast.show({
                type: 'error',
                text1: '退出失败',
                text2: '请稍后重试',
              });
            }
          },
        },
      ],
      { cancelable: true }
    );
  };

  const renderArtworkItem = ({ item }: { item: ArtworkResponse }) => (
    <TouchableOpacity 
      style={[styles.artworkItem, { backgroundColor: theme.colors.card }]}
      onPress={() => router.push({ pathname: '/artwork/[id]', params: { id: item.id } })}
    >
      <View style={styles.artworkImageContainer}>
        {item.file_type.startsWith('image/') ? (
          <Image
            source={{ 
              uri: item.file_url.startsWith('http') 
                ? item.file_url 
                : `${API_BASE_URL}${item.file_url}` 
            }}
            style={styles.artworkImage}
          />
        ) : (
          <View style={[styles.fileTypeIconContainer, { backgroundColor: theme.colors.background }]}>
            <MaterialIcons 
              name={getFileTypeIcon(item.file_type)} 
              size={40} 
              color={theme.colors.text} 
            />
          </View>
        )}
      </View>
      <View style={styles.artworkInfo}>
        <Text style={[styles.artworkTitle, { color: theme.colors.text }]} numberOfLines={1}>{item.title}</Text>
        <Text style={[styles.artworkDescription, { color: theme.colors.placeholder }]} numberOfLines={2}>
          {item.description || '暂无描述'}
        </Text>
        <View style={styles.artworkMeta}>
          <Text style={[styles.artworkCategory, { backgroundColor: theme.colors.primary + '20', color: theme.colors.primary }]}>
            {item.category}
          </Text>
          <Text style={[styles.artworkDate, { color: theme.colors.placeholder }]}>
            {new Date(item.created_at).toLocaleDateString()}
          </Text>
        </View>
      </View>
    </TouchableOpacity>
  );

  const renderTopicItem = ({ item }: { item: TopicResponse }) => (
    <TouchableOpacity 
      style={[styles.topicItem, { backgroundColor: theme.colors.card }]}
      onPress={() => router.push({ pathname: '/topic/[id]', params: { id: item.id } })}
    >
      <View style={styles.topicContent}>
        <Text style={[styles.topicTitle, { color: theme.colors.text }]} numberOfLines={1}>{item.title}</Text>
        <Text style={[styles.topicText, { color: theme.colors.placeholder }]} numberOfLines={2}>{item.content}</Text>
      </View>
      <View style={styles.topicFooter}>
        <View style={styles.topicStats}>
          <View style={styles.topicStat}>
            <MaterialIcons name="thumb-up" size={16} color={theme.colors.placeholder} />
            <Text style={[styles.topicStatText, { color: theme.colors.placeholder }]}>{item.like_count}</Text>
          </View>
          <Text style={[styles.topicDate, { color: theme.colors.placeholder }]}>{formatDate(item.created_at)}</Text>
        </View>
      </View>
    </TouchableOpacity>
  );

  return (
    <ScrollView 
      style={[styles.container, { backgroundColor: theme.colors.background }]}
      refreshControl={
        <RefreshControl
          refreshing={refreshing}
          onRefresh={onRefresh}
          colors={[theme.colors.primary]} // Android
          tintColor={theme.colors.primary} // iOS
        />
      }
    >
      <View style={[styles.header, { backgroundColor: theme.colors.card, borderBottomColor: theme.colors.border }]}>
        {userInfo?.avatar && (
          <Image
            source={{ 
              uri: userInfo.avatar.includes('?') 
                ? userInfo.avatar 
                : userInfo.avatar.startsWith('http')
                  ? `${userInfo.avatar}?t=${Date.now()}`
                  : `${API_BASE_URL}${userInfo.avatar}?t=${Date.now()}`
            }}
            style={styles.avatar}
          />
        )}
        <View style={styles.userInfo}>
          <Text style={[styles.nickname, { color: theme.colors.text }]}>{userInfo?.nickname || '未设置昵称'}</Text>
          <Text style={[styles.username, { color: theme.colors.placeholder }]}>@{userInfo?.username || ''}</Text>
          <Text style={[styles.bio, { color: theme.colors.placeholder }]}>{userInfo?.bio || '这个人很懒，什么都没写~'}</Text>
        </View>
        <TouchableOpacity 
          style={[styles.editButton, { backgroundColor: theme.colors.card }]} 
          onPress={handleEditProfile}
        >
          <MaterialIcons name="edit" size={20} color={theme.colors.text} />
          <Text style={[styles.editButtonText, { color: theme.colors.text }]}>编辑资料</Text>
        </TouchableOpacity>
      </View>

      {/* 主题设置部分 */}
      <View style={[styles.section, { backgroundColor: theme.colors.card }]}>
        <Text style={[styles.sectionTitle, { color: theme.colors.text }]}>主题设置</Text>
        <ThemeToggle />
      </View>

      <View style={[styles.section, { backgroundColor: theme.colors.card }]}>
        <Text style={[styles.sectionTitle, { color: theme.colors.text }]}>我的作品</Text>
        {artworks.length === 0 ? (
          <View style={styles.emptyContainer}>
            <MaterialIcons name="image" size={40} color={theme.colors.placeholder} />
            <Text style={[styles.emptyText, { color: theme.colors.placeholder }]}>暂无作品</Text>
            <TouchableOpacity 
              style={[styles.uploadButton, { backgroundColor: theme.colors.primary }]}
              onPress={() => router.push('/artwork/create')}
            >
              <Text style={styles.uploadButtonText}>上传作品</Text>
            </TouchableOpacity>
          </View>
        ) : (
          <FlatList
            data={artworks}
            renderItem={renderArtworkItem}
            keyExtractor={item => item.id.toString()}
            horizontal={false}
            scrollEnabled={false}
            ItemSeparatorComponent={() => <View style={[styles.separator, { backgroundColor: theme.colors.border }]} />}
          />
        )}
      </View>

      <View style={[styles.section, { backgroundColor: theme.colors.card }]}>
        <Text style={[styles.sectionTitle, { color: theme.colors.text }]}>我的话题</Text>
        {topics.length === 0 ? (
          <View style={styles.emptyContainer}>
            <MaterialIcons name="forum" size={40} color={theme.colors.placeholder} />
            <Text style={[styles.emptyText, { color: theme.colors.placeholder }]}>暂无话题</Text>
            <TouchableOpacity 
              style={[styles.uploadButton, { backgroundColor: theme.colors.primary }]}
              onPress={() => router.push('/topic/create')}
            >
              <Text style={styles.uploadButtonText}>发布话题</Text>
            </TouchableOpacity>
          </View>
        ) : (
          <FlatList
            data={topics}
            renderItem={renderTopicItem}
            keyExtractor={item => item.id.toString()}
            horizontal={false}
            scrollEnabled={false}
            ItemSeparatorComponent={() => <View style={[styles.separator, { backgroundColor: theme.colors.border }]} />}
          />
        )}
      </View>

      <TouchableOpacity 
        style={[styles.logoutButton, { backgroundColor: theme.colors.card }]} 
        onPress={handleLogout}
      >
        <MaterialIcons name="logout" size={20} color="#FF4444" />
        <Text style={styles.logoutButtonText}>退出登录</Text>
      </TouchableOpacity>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  header: {
    backgroundColor: '#fff',
    padding: 20,
    alignItems: 'center',
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  avatar: {
    width: 80,
    height: 80,
    borderRadius: 40,
    marginBottom: 12,
  },
  userInfo: {
    alignItems: 'center',
  },
  nickname: {
    fontSize: 20,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 4,
  },
  username: {
    fontSize: 14,
    color: '#666',
    marginBottom: 8,
  },
  bio: {
    fontSize: 14,
    color: '#666',
    textAlign: 'center',
    marginBottom: 16,
  },
  editButton: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#f5f5f5',
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 20,
  },
  editButtonText: {
    marginLeft: 4,
    fontSize: 14,
    color: '#666',
  },
  section: {
    backgroundColor: '#fff',
    padding: 16,
    marginTop: 12,
  },
  sectionTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 12,
  },
  emptyText: {
    fontSize: 14,
    color: '#999',
    textAlign: 'center',
    marginVertical: 20,
  },
  logoutButton: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#fff',
    marginTop: 20,
    marginBottom: 40,
    padding: 16,
  },
  logoutButtonText: {
    marginLeft: 8,
    fontSize: 16,
    color: '#FF4444',
  },
  artworkItem: {
    flexDirection: 'row',
    borderRadius: 8,
    overflow: 'hidden',
    marginBottom: 12,
    elevation: 2,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
  },
  artworkImageContainer: {
    width: 100,
    height: 100,
    backgroundColor: '#f5f5f5',
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 8,
    overflow: 'hidden',
  },
  fileTypeIconContainer: {
    width: 100,
    height: 100,
    justifyContent: 'center',
    alignItems: 'center',
  },
  artworkImage: {
    width: 100,
    height: 100,
    backgroundColor: '#f5f5f5',
  },
  artworkInfo: {
    flex: 1,
    padding: 12,
  },
  artworkTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 4,
  },
  artworkDescription: {
    fontSize: 14,
    marginBottom: 8,
  },
  artworkMeta: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  artworkCategory: {
    fontSize: 12,
    paddingHorizontal: 8,
    paddingVertical: 2,
    borderRadius: 4,
  },
  artworkDate: {
    fontSize: 12,
  },
  separator: {
    height: 1,
    backgroundColor: '#eee',
    marginVertical: 8,
  },
  emptyContainer: {
    alignItems: 'center',
    padding: 32,
  },
  uploadButton: {
    marginTop: 16,
    backgroundColor: '#007AFF',
    paddingHorizontal: 20,
    paddingVertical: 10,
    borderRadius: 20,
  },
  uploadButtonText: {
    color: '#fff',
    fontSize: 14,
    fontWeight: '500',
  },
  topicItem: {
    borderRadius: 8,
    padding: 12,
    marginBottom: 8,
    elevation: 2,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
  },
  topicContent: {
    flex: 1,
  },
  topicTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 4,
  },
  topicText: {
    fontSize: 14,
    marginBottom: 8,
  },
  topicFooter: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginTop: 8,
  },
  topicStats: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  topicStat: {
    flexDirection: 'row',
    alignItems: 'center',
    marginRight: 16,
  },
  topicStatText: {
    fontSize: 12,
    marginLeft: 4,
  },
  topicDate: {
    fontSize: 12,
  },
}); 